package com.hsyt.pfc.support.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.conn.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


/**
 * @Description: 网络工具类
 * @ClassName: WebUtils.java
 * @Package: com.hsyt.pfc.pay.support.channel.util
 * @Author: jinren12516
 * @Date: 2016年4月6日 下午3:44:57
 * @CopyRight: 版权归Hundsun 所有
 * <ModifyLog>
 * @ModifyContent:
 * @Author:
 * @Date: </ModifyLog>
 */

public abstract class WebUtils {

    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final String METHOD_POST = "POST";
    private static final String METHOD_GET = "GET";
    private static final Logger logger = LoggerFactory.getLogger(WebUtils.class);

    private static class DefaultTrustManager implements X509TrustManager {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    }

    private WebUtils() {
    }

    /**
     * @Desciption: 执行HTTP-POST请求
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午4:00:44
     */
    public static String doPost(String url, Map<String, String> params, byte[] keyFile, String key, int connectTimeout, int readTimeout) throws IOException {
        return doPost(url, params, DEFAULT_CHARSET, keyFile, key, connectTimeout, readTimeout);
    }

    /**
     * @Desciption: 执行HTTP-POST请求
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午4:01:52
     */
    public static String doPost(String url, Map<String, String> params, String charset, byte[] keyFile, String key, int connectTimeout, int readTimeout) throws IOException {
        String ctype = "application/x-www-form-urlencoded;charset=" + charset;
        String query = buildQuery(params, charset);
        byte[] content = {};
        if (query != null) {
            content = query.getBytes(charset);
        }
        return doPost(url, ctype, content, keyFile, key, connectTimeout, readTimeout);
    }

    /**
     * 增加鉴权参数header请求参数
     * <strong>Time</strong>:2017年4月20日,下午12:50:40<br>
     * <strong>Author</strong>
     * <changeLog>
     * </changeLog>
     */
    private static void addHeader(final HttpURLConnection conn, final Map<String, String> headerParams) {
        if (conn != null && headerParams != null) {
            Iterator<String> iterator = headerParams.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                conn.setRequestProperty(key, headerParams.get(key));
            }
        }
    }

    /**
     * 增加鉴权请求参数
     * <strong>Time</strong>:2017年4月20日,下午12:51:05<br>
     * <strong>Author</strong>
     * <changeLog>
     * </changeLog>
     */
    public static String doPost(Map<String, String> headerParams, String url, String ctype, byte[] content, byte[] keyFile, String key, int connectTimeout, int readTimeout) throws IOException {
        HttpURLConnection conn = null;
        OutputStream out = null;
        String rsp = null;
        try {
            try {
                conn = getConnection(new URL(url), METHOD_POST, ctype, keyFile, key);
                addHeader(conn, headerParams);//增加token值
                conn.setConnectTimeout(connectTimeout);
                conn.setReadTimeout(readTimeout);
            } catch (IOException e) {
                logger.error("exception error: " + e);
                throw e;
            }
            try {
                out = conn.getOutputStream();
                out.write(content);
                rsp = getResponseAsString(conn);
            } catch (IOException e) {
                logger.error("exception error: " + e);
                throw e;
            }

        } catch (Exception e) {
            logger.error("WebUtils.doPost(url=" + url + ",params: " + content.toString() + "), rsp =  " + rsp + "exception error: " + e);
            throw e;
        } finally {
            if (out != null) {
                out.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rsp;
    }

    /**
     * @Desciption: 执行HTTP-POST请求
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午4:01:13
     */
    public static String doPost(String url, String ctype, byte[] content, byte[] keyFile, String key, int connectTimeout, int readTimeout) throws IOException {
        HttpURLConnection conn = null;
        OutputStream out = null;
        String rsp = null;
        try {
            try {
                conn = getConnection(new URL(url), METHOD_POST, ctype, keyFile, key);
                conn.setConnectTimeout(connectTimeout);
                conn.setReadTimeout(readTimeout);

            } catch (IOException e) {
                logger.error("exception error: " + e);
                throw e;
            }
            try {
                out = conn.getOutputStream();
                out.write(content);
                rsp = getResponseAsString(conn);
            } catch (IOException e) {
                logger.error("exception error: " + e);
                throw e;
            }

        } catch (Exception e) {
            logger.error("WebUtils.doPost(url=" + url + ",params: " + content.toString() + "), rsp =  " + rsp + "exception error: " + e);
            throw e;
        } finally {
            if (out != null) {
                out.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rsp;
    }

    /**
     * @Desciption: 执行HTTP-POST请求
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午3:59:35
     */
    public static String doPost(String url, Map<String, String> params, Map<String, FileItem> fileParams, byte[] keyFile, String key, int connectTimeout, int readTimeout) throws IOException {
        if (fileParams == null || fileParams.isEmpty()) {
            return doPost(url, params, DEFAULT_CHARSET, keyFile, key, connectTimeout, readTimeout);
        } else {
            return doPost(url, params, fileParams, DEFAULT_CHARSET, keyFile, key, connectTimeout, readTimeout);
        }
    }

    /**
     * @Desciption: 执行HTTP-POST请求
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午3:59:21
     */
    public static String doPost(String url, Map<String, String> params, Map<String, FileItem> fileParams, String charset, byte[] keyFile, String key, int connectTimeout, int readTimeout) throws IOException {
        if (fileParams == null || fileParams.isEmpty()) {
            return doPost(url, params, charset, keyFile, key, connectTimeout, readTimeout);
        }
        String boundary = System.currentTimeMillis() + ""; // 随机分隔线
        HttpURLConnection conn = null;
        OutputStream out = null;
        String rsp = null;
        try {
            try {
                String ctype = "multipart/form-data;boundary=" + boundary + ";charset=" + charset;
                conn = getConnection(new URL(url), METHOD_POST, ctype, keyFile, key);
                conn.setConnectTimeout(connectTimeout);
                conn.setReadTimeout(readTimeout);
            } catch (IOException e) {
                logger.error("exception error: " + e);
                throw e;
            }
            try {
                out = conn.getOutputStream();
                byte[] entryBoundaryBytes = ("\r\n--" + boundary + "\r\n").getBytes(charset);
                // 组装文本请求参数
                Set<Entry<String, String>> textEntrySet = params.entrySet();
                for (Entry<String, String> textEntry : textEntrySet) {
                    byte[] textBytes = getTextEntry(textEntry.getKey(), textEntry.getValue(),
                            charset);
                    out.write(entryBoundaryBytes);
                    out.write(textBytes);
                }
                // 组装文件请求参数
                Set<Entry<String, FileItem>> fileEntrySet = fileParams.entrySet();
                for (Entry<String, FileItem> fileEntry : fileEntrySet) {
                    FileItem fileItem = fileEntry.getValue();
                    byte[] fileBytes = getFileEntry(fileEntry.getKey(), fileItem.getFieldName(), fileItem.getContentType(), charset);
                    out.write(entryBoundaryBytes);
                    out.write(fileBytes);
//                    out.write(fileItem.getContent());
                }
                // 添加请求结束标志
                byte[] endBoundaryBytes = ("\r\n--" + boundary + "--\r\n").getBytes(charset);
                out.write(endBoundaryBytes);
                rsp = getResponseAsString(conn);
            } catch (IOException e) {
                logger.error("exception error: " + e);
                throw e;
            }

        } finally {
            if (out != null) {
                out.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rsp;
    }

    private static byte[] getTextEntry(String fieldName, String fieldValue, String charset) throws IOException {
        StringBuilder entry = new StringBuilder();
        entry.append("Content-Disposition:form-data;name=\"");
        entry.append(fieldName);
        entry.append("\"\r\nContent-Type:text/plain\r\n\r\n");
        entry.append(fieldValue);
        return entry.toString().getBytes(charset);
    }

    private static byte[] getFileEntry(String fieldName, String fileName, String mimeType, String charset) throws IOException {
        StringBuilder entry = new StringBuilder();
        entry.append("Content-Disposition:form-data;name=\"");
        entry.append(fieldName);
        entry.append("\";filename=\"");
        entry.append(fileName);
        entry.append("\"\r\nContent-Type:");
        entry.append(mimeType);
        entry.append("\r\n\r\n");
        return entry.toString().getBytes(charset);
    }

    /**
     * @Desciption: 执行HTTP-GET请求
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午3:58:51
     */
    public static String doGet(String url, Map<String, String> params, byte[] keyFile, String key) throws IOException {
        return doGet(url, params, DEFAULT_CHARSET, keyFile, key);
    }

    /**
     * @Desciption: 执行HTTP-GET请求
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午3:58:45
     */
    public static String doGet(String url, Map<String, String> params, String charset, byte[] keyFile, String key) throws IOException {
        HttpURLConnection conn = null;
        String rsp = null;
        try {
            String ctype = "application/x-www-form-urlencoded;charset=" + charset;
            String query = buildQuery(params, charset);
            try {
                conn = getConnection(buildGetUrl(url, query), METHOD_GET, ctype, keyFile, key);
            } catch (IOException e) {
                logger.error("exception error: " + e);
                throw e;
            }
            try {
                rsp = getResponseAsString(conn);
            } catch (IOException e) {
                logger.error("exception error: " + e);
                throw e;
            }
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return rsp;
    }

    /**
     * @Desciption: 获取HTTP连接
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午3:58:29
     */
    private static HttpURLConnection getConnection(URL url, String method, String ctype, byte[] keyFile, String key) throws IOException {
        HttpURLConnection conn = null;
        if ("https".equals(url.getProtocol())) {
            SSLContext ctx = null;
            if (keyFile == null && StringUtils.isBlank(key)) {
                try {
                    ctx = SSLContext.getInstance("TLS");
                    ctx.init(new KeyManager[0], new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
                } catch (Exception e) {
                    throw new IOException(e);
                }
            } else {
                InputStream inputStream = new ByteArrayInputStream(keyFile, 512, 2048);
                try {
                    KeyStore keyStore = KeyStore.getInstance("PKCS12");
                    keyStore.load(inputStream, key.toCharArray());
                    ctx = SSLContexts.custom().loadKeyMaterial(keyStore, key.toCharArray()).build();
                } catch (CertificateException e) {
                    e.printStackTrace();
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (KeyManagementException e) {
                    e.printStackTrace();
                } catch (UnrecoverableKeyException e) {
                    e.printStackTrace();
                } catch (KeyStoreException e) {
                    e.printStackTrace();
                } finally {
                    inputStream.close();
                }
//	            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, Configure.getCertPassword().toCharArray()).build();
//	            // Allow TLSv1 protocol only
//	            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
//	                    sslcontext,
//	                    new String[]{"TLSv1"},
//	                    null,
//	                    SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            }

            HttpsURLConnection connHttps = (HttpsURLConnection) url.openConnection();
            connHttps.setSSLSocketFactory(ctx.getSocketFactory());
            connHttps.setHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return false; // 默认认证不通过，进行证书校验。
                }
            });
            conn = connHttps;
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html,application/xhtml+xml,application/xml,application/json");
        conn.setRequestProperty("User-Agent", "aop-sdk-java");
        conn.setRequestProperty("Content-Type", ctype);
        return conn;
    }

    /**
     * @Desciption: 获取请求URL
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午3:58:08
     */
    private static URL buildGetUrl(String strUrl, String query) throws IOException {
        URL url = new URL(strUrl);
        if (StringUtils.isEmpty(query)) {
            return url;
        }
        if (StringUtils.isEmpty(url.getQuery())) {
            if (strUrl.endsWith("?")) {
                strUrl = strUrl + query;
            } else {
                strUrl = strUrl + "?" + query;
            }
        } else {
            if (strUrl.endsWith("&")) {
                strUrl = strUrl + query;
            } else {
                strUrl = strUrl + "&" + query;
            }
        }
        return new URL(strUrl);
    }

    /**
     * @Desciption: 拼接参数
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午3:57:35
     */
    public static String buildQuery(Map<String, String> params, String charset) throws IOException {
        if (params == null || params.isEmpty()) {
            return null;
        }
        StringBuilder query = new StringBuilder();
        Set<Entry<String, String>> entries = params.entrySet();
        boolean hasParam = false;
        for (Entry<String, String> entry : entries) {
            String name = entry.getKey();
            String value = entry.getValue();
            // 忽略参数名或参数值为空的参数
            if (StringUtils.isNotBlank(entry.getValue())) {
                if (hasParam) {
                    query.append("&");
                } else {
                    hasParam = true;
                }
                query.append(name).append("=").append(URLEncoder.encode(value, charset));
            }
        }
        return query.toString();
    }

    /**
     * @Desciption: 将RESPONSE结果转为STRING字符串
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午3:56:56
     */
    protected static String getResponseAsString(HttpURLConnection conn) throws IOException {
        String charset = getResponseCharset(conn.getContentType());
        InputStream es = conn.getErrorStream();
        if (es == null) {
            return getStreamAsString(conn.getInputStream(), charset);
        } else {
            String msg = getStreamAsString(es, charset);
            if (StringUtils.isEmpty(msg)) {
                throw new IOException(conn.getResponseCode() + ":" + conn.getResponseMessage());
            } else {
                logger.error("throw new IOException(msg): " + msg);
                throw new IOException(msg);
            }
        }
    }

    /**
     * @Desciption: 将RESPONSE流转为STRING字符串
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午3:56:28
     */
    private static String getStreamAsString(InputStream stream, String charset) throws IOException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
            StringWriter writer = new StringWriter();

            char[] chars = new char[256];
            int count = 0;
            while ((count = reader.read(chars)) > 0) {
                writer.write(chars, 0, count);
            }
            return writer.toString();
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }

    /**
     * @Desciption: 获取RESPONSE中的编码集
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午3:55:20
     */
    private static String getResponseCharset(String ctype) {
        String charset = DEFAULT_CHARSET;

        if (!StringUtils.isEmpty(ctype)) {
            String[] params = ctype.split(";");
            for (String param : params) {
                param = param.trim();
                if (param.startsWith("charset")) {
                    String[] pair = param.split("=", 2);
                    if (pair.length == 2) {
                        if (!StringUtils.isEmpty(pair[1])) {
                            charset = pair[1].trim();
                        }
                    }
                    break;
                }
            }
        }
        return charset;
    }

    /**
     * @Desciption: 使用默认的UTF-8字符集反编码请求参数值
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午3:55:53
     */
    public static String decode(String value) {
        return decode(value, DEFAULT_CHARSET);
    }

    /**
     * @Desciption: 使用默认的UTF-8字符集编码请求参数值
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午3:56:02
     */
    public static String encode(String value) {
        return encode(value, DEFAULT_CHARSET);
    }

    /**
     * @Desciption: 使用指定的字符集反编码请求参数值
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午3:56:09
     */
    public static String decode(String value, String charset) {
        String result = null;
        if (!StringUtils.isEmpty(value)) {
            try {
                result = URLDecoder.decode(value, charset);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return result;
    }

    /**
     * @Desciption: 使用指定的字符集编码请求参数值
     * @Author: jinren12516
     * @Date: 2016年4月6日 下午3:56:16
     */
    public static String encode(String value, String charset) {
        String result = null;
        if (!StringUtils.isEmpty(value)) {
            try {
                result = URLEncoder.encode(value, charset);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return result;
    }
}
